<template>
    <v-card class="elevation-12 showOrder">
        <v-toolbar
                color="primary"
                dark
                flat
        >
            <v-toolbar-title>后端登录</v-toolbar-title>
            <v-spacer></v-spacer>
        </v-toolbar>
        <v-card-text>
            <v-form>
                <v-text-field
                        v-model="username"
                        :rules="[ checkValue ]"
                        label="用户名"
                        name="login"
                        prepend-icon="mdi-account"
                        type="text"
                ></v-text-field>

                <v-text-field
                        v-model="password"
                        :rules="[ checkValue ]"
                        label="密码"
                        name="password"
                        prepend-icon="mdi-lock"
                        type="password"
                ></v-text-field>
            </v-form>
        </v-card-text>
        <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" @click="toLogin">登录</v-btn>
        </v-card-actions>
    </v-card>
</template>

<script>
  /**
   * 用户登录的表单组件
   */
  export default {
    name: 'LoginComponent',
    data() {
      return {
        username: '',
        password: ''
      }
    },
    methods: {
      async toLogin() {
        if (this.username.trim() == 0) {
          alert('用户名不允许使用空字符串');
        }
        if (this.password.trim() == 0) {

          alert('密码不允许使用空字符串');
        }
        try {
          const {data: res} = await this.$http.post('/toLogin', {
            userName: this.username,
            password: this.password
          })
          if (res.errorCode == 200) {
            console.log(res);
            //this.setCookie(res.data)
            alert('登录成功');
            window.localStorage.setItem('authToken', res.data);

            if(this.$route.path==='/login'){
              this.$router.push('/manager')
            }else {
              // 当修改文章的时候，中间如果重新登录这个时候不进行跳转,
              // 只需要将登录组件隐藏即可。
              this.$store.commit('setShowDialogToFalse');
            }
          } else {
            alert(res.message);
          }
        } catch (e) {
          alert('登录失败，可能是网络原因，请重试！');
        }
      },
      checkValue(value) {
        console.log("path:");
        console.log(this.$route);
        // 用户名和密码的校验规则
        if (value.trim().length === 0) {
          this.disabled = true;
          return '用户名或密码不允许为空';
        } else {
          return true;
        }
      }

    }
  }
</script>

<style scoped>

</style>